package com.young.jdbc.datasource;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.junit.Test;

import java.io.FileInputStream;
import java.sql.Connection;
import java.util.Properties;

/**
 * @Author: young
 * @Date: 2021-12-03 15:51
 * @Description: C3P0数据库连接池的使用
 */
public class C3P0_demo {
	// 方式1：相关参数，在程序指定user，url，password等
	@Test
	public void P3C0_test1() throws Exception {
		// 创建一个数据源对象
		ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
		// 通过配置文件获取相关信息
		Properties properties = new Properties();
		properties.load(new FileInputStream("src\\mysql.properties"));

		String url = properties.getProperty("url");
		String user = properties.getProperty("user");
		String password = properties.getProperty("password");
		String driver = properties.getProperty("driver");

		// 给数据源comboPooledDataSource设置相关参数
		// 连接的管理是由comboPooledDataSource来管理的
		comboPooledDataSource.setDriverClass(driver);
		comboPooledDataSource.setJdbcUrl(url);
		comboPooledDataSource.setUser(user);
		comboPooledDataSource.setPassword(password);

		// 设置初始化连接数
		comboPooledDataSource.setInitialPoolSize(10);
		// 最大连接数
		comboPooledDataSource.setMaxPoolSize(50);
		// 测试连接池的效率
		long start = System.currentTimeMillis();
		for (int i=0; i<5000;i++){
			Connection connection = comboPooledDataSource.getConnection();	//这个方法就是从DataSource接口实现的
			// System.out.println("连接成功");
			connection.close();
		}
		long end = System.currentTimeMillis();
		System.out.println("C3P0连接5000次MySQL 耗时为"+(end-start));
	}

	// 方式2：使用配置文件模板来完成(c3p0-config.xml)
	@Test
	public void P3C0_test2() throws Exception {
		// 创建一个数据源对象
		ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource("properties");
		// 测试连接池的效率
		long start = System.currentTimeMillis();
		for (int i=0; i<5000;i++){
			Connection connection = comboPooledDataSource.getConnection();	//这个方法就是从DataSource接口实现的
			// System.out.println("连接成功");
			connection.close();
		}
		long end = System.currentTimeMillis();
		System.out.println("C3P0连接5000次MySQL 耗时为"+(end-start));
	}
}
